#include "../include/mysql_manager.h"
#include <iostream>

namespace util {

MySQLManager::MySQLManager(const std::string &host, const std::string &user, const std::string &password, const std::string &db)
{
    _conn = mysql_init(nullptr);
    if (!_conn) {
        std::cerr << "MySQL initialization failed!" << std::endl;
        return;
    }
    if (!mysql_real_connect(_conn, host.c_str(), user.c_str(), password.c_str(), db.c_str(), 0, nullptr, 0)) 
    {
        std::cerr << "MySQL connection failed: " << mysql_error(_conn) << std::endl;
        mysql_close(_conn);
        _conn = nullptr;
    }
}

MySQLManager::~MySQLManager()
{
    if (_conn) 
    {
        mysql_close(_conn);
    }
}

bool MySQLManager::registerUser(const std::string &username, const std::string &password)
{
    std::string query = "INSERT INTO users (username, password) VALUES ('" + username + "', '" + password + "')";
    if (mysql_query(_conn, query.c_str())) 
    {
        std::cerr << "Register user failed: " << mysql_error(_conn) << std::endl;
        return false;
    }
    return true;
}

bool MySQLManager::loginUser(const std::string &username, const std::string &password)
{
    std::string query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
    if (mysql_query(_conn, query.c_str())) 
    {
        std::cerr << "Login user failed: " << mysql_error(_conn) << std::endl;
        return false;
    }
    MYSQL_RES *res = mysql_store_result(_conn);
    bool success = (mysql_num_rows(res) > 0);
    mysql_free_result(res);
    return success;
}

} // namespace util
